const app = getApp()
const util = require("../../../util/util.js")
import { deleteImgApi, deleteVideoApi } from "../../../api/api.js"

Page({
  data: {
    superviseContentList: [],
    accounts: [],
    accountIndex: -1,
    currentIndex: -1,
    isDelelte: 0
  },
  onLoad: function (options) {
    this.getSuperviseContent()
    this.getCategoryList()
  },

  onUnload: function (e) {
    if (this.data.isDelelte == 0) {
      for (let i = 0; i < this.data.superviseContentList.length; i++) {
        if (this.data.superviseContentList[i].imageUrl == null) continue
        for (let j = 0; j < this.data.superviseContentList[i].imageUrl.length; j++) {
          let target = this.data.superviseContentList[i].imageUrl[j]
          deleteImgApi(target.split("image/")[1]).then((res) => {
            if (res.data == "success") {
              console.log("图片删除")
            }
          })
        }
        if (this.data.superviseContentList[i].video == "") continue
        deleteVideoApi(this.data.superviseContentList[i].video.split("video/")[1]).then((res) => {
          if (res.data == "success") {
            console.log("视频删除")
          }
        })
      }
    }
  },

  // onShow: function () {
  //   this.getSuperviseContent()
  // },


  inputContent: function (e) {
    e.detail.value = app.trim(e.detail.value)
    let index = parseInt(e.target.id.split('-')[1]),
      superviseContentList = this.data.superviseContentList
    superviseContentList[index].contentLength = parseInt(e.detail.value.length)
    superviseContentList[index].recordContent = e.detail.value
    this.setData({
      superviseContentList: superviseContentList
    })
  },

  switchChange: function (e) {
    console.log("e", e.currentTarget.id)
    let contentIndex = parseInt(e.currentTarget.id.split('-')[1])
    let superviseContentList = this.data.superviseContentList
    if (e.detail.value == false) {
      superviseContentList[contentIndex].normal = -1
      superviseContentList[contentIndex].contentLength = 0
      superviseContentList[contentIndex].dealFiles = []
      superviseContentList[contentIndex].imageUrl = []
      superviseContentList[contentIndex].hide = false
      superviseContentList[contentIndex].imageNum = 0
      superviseContentList[contentIndex].recordContent = ""
      superviseContentList[contentIndex].video = ""
      superviseContentList[contentIndex].videoSrc = ""
      superviseContentList[contentIndex].selectedIndex = null
      superviseContentList[contentIndex].modalComfirm = null
      superviseContentList[contentIndex].modalName = null
      superviseContentList[contentIndex].waringInfo = ""
    } else {
      superviseContentList[contentIndex].normal = 0
      superviseContentList[contentIndex].recordContent = ""
      superviseContentList[contentIndex].video = ""
      superviseContentList[contentIndex].videoSrc = ""
      superviseContentList[contentIndex].selectedIndex = null
      superviseContentList[contentIndex].modalComfirm = null
      superviseContentList[contentIndex].modalName = null
      superviseContentList[contentIndex].waringInfo = ""
    }
    this.setData({
      superviseContentList: superviseContentList,
    })
  },

  getSuperviseContent() {
    dd.httpRequest({
      url: app.baseUrl + '/DingDing/Supervise/getSuperviseContentById',
      method: "GET",
      data: {
        id: app.globalData.superviseId,
        schoolId: app.globalData.superviseSchoolId,
        userId: app.globalData.userId
      },
      dataType: 'json',
      success: res => {
        this.setData({
          superviseContentList: res.data
        })
      }
    })
  },

  submit: util.throttle(function (e) {
    let index = e.currentTarget.dataset.index
    let normal = this.data.superviseContentList[index].normal == 0 ? 1 : 2
    if (normal == 2) {
      let waringInfoStr = 'superviseContentList[' + index + '].waringInfo'
      this.setData({
        [waringInfoStr]: ""
      })
      if (this.data.superviseContentList[index].selectedIndex == null) {
        this.setData({
          [waringInfoStr]: "请选择隐患类型"
        })
      } else if (this.data.superviseContentList[index].recordContent == "" || !this.data.superviseContentList[index].recordContent) {
        this.setData({
          [waringInfoStr]: "请输入详细问题"
        })
      } else if (this.data.superviseContentList[index].imageUrl == null || this.data.superviseContentList[index].imageUrl.length == 0) {
        this.setData({
          [waringInfoStr]: "请上传照片"
        })
      }
      if (this.data.superviseContentList[index].waringInfo != "") {
        dd.showToast({
          content: this.data.superviseContentList[index].waringInfo
        })
        return
      }
    }

    this.setData({
      isDelelte: 1
    })
    let superviseContent = e.currentTarget.dataset.supervisecontent
    let categoryId = this.data.categoryId[this.data.superviseContentList[index].selectedIndex]
    let createTime = util.formatTime(new Date())
    let modifyTime = util.formatTime(new Date())
    let superviseContentId = e.currentTarget.dataset.supervisecontentid
    dd.showLoading({
      content: '正在提交'
    })
    dd.httpRequest({
      url: app.baseUrl + '/DingDing/Supervise/submitSupervise',
      method: 'POST',
      headers: {
        "Content-Type": "application/json"
      },
      data: JSON.stringify({
        userId: app.globalData.userId,
        superviseRelationId: app.globalData.superviseId,
        normal: normal,
        superviseContent: superviseContent,
        createTime: createTime,
        modifyTime: modifyTime,
        superviseContentId: superviseContentId
      }),
      dataType: 'json',
      success: res => {
        if (res.data.res == "success") {
          let superviseContentListStr = 'superviseContentList[' + index + '].normal'
          this.setData({
            [superviseContentListStr]: normal
          })
          if (normal == 1) {
            dd.showToast({
              content: '提交成功'
            })
          } else if (normal == 2) {
            dd.httpRequest({
              url: app.baseUrl + '/DingDingSystem/safetyReport',
              method: 'POST',
              headers: {
                "Content-Type": "application/json"
              },
              data: JSON.stringify({
                schoolId: app.globalData.superviseSchoolId,
                safetyLevel: 2,
                address: app.globalData.superviseSchoolName,
                content: this.data.superviseContentList[index].recordContent,
                photo: this.data.superviseContentList[index].imageUrl.join(","),
                video: this.data.superviseContentList[index].video,
                reporter: app.globalData.userId,
                categoryId: categoryId,
                inspectConditionId: -1,
                superviseId: res.data.id
              }),
              dataType: 'json',
              success: res => {
                if (res.data.res == "success") {
                  let safetySceneId = res.data.data
                  dd.httpRequest({
                    url: app.baseUrl + '/DingDingSystem/getAccessTokenForSendMsg',
                    method: 'GET',
                    data: {
                      schoolId: app.globalData.departmentId
                    },
                    dataType: 'json',
                    success: res => {
                      console.log("res", res)
                      let access_token = res.data.access_token
                      dd.httpRequest({
                        url: app.baseUrl + '/DingDingSystem/getChargeManDingDingId',
                        method: 'POST',
                        headers: {
                          "Content-Type": "application/json"
                        },
                        data: JSON.stringify({
                          categoryId: categoryId,
                          schoolId: app.globalData.superviseSchoolId,
                        }),
                        dataType: 'json',
                        success: res => {

                          let unbind = []
                          for (let i = 0; i < res.data.length; i++) {
                            if (res.data[i].res == "success") {
                              let datetime = util.formatTime(new Date())
                              dd.httpRequest({
                                url: app.baseUrl + '/DingDingSystem/sendMessage',
                                method: 'POST',
                                headers: {
                                  "Content-Type": "application/json"
                                },
                                dataType: 'json',
                                data: JSON.stringify({
                                  schoolId: app.globalData.departmentId,
                                  template: 1,
                                  accessToken: access_token,
                                  touser: res.data[i].msg,
                                  safetySceneId: safetySceneId,
                                  data: {
                                    first: {
                                      value: "【巡查异常】"
                                    },
                                    keyword1: {
                                      value: app.globalData.realname
                                    },
                                    keyword2: {
                                      value: datetime
                                    },
                                    keyword3: {
                                      value: `巡查时发现异常，请及时查看!`
                                    }
                                  }
                                })


                              })
                            } else {
                              unbind.push(res.data[i].msg)
                            }
                          }
                        }
                      })
                    }
                  })
                } else {
                  dd.showToast({
                    content: '上报失败'
                  })
                }
              },
              fail: res => {
                dd.showToast({
                  content: '网络异常！'
                })
              }
            })
          }

        }
      },
      complete: () => {
        dd.hideLoading()
      }
    })


  }, 1000),


  getCategoryList: function () {
    dd.httpRequest({
      url: app.baseUrl + '/DingDingSystem/getAllValidInspectItems',
      method: 'POST',
      headers: {
        "Content-Type": "application/json"
      },
      data: JSON.stringify({
        schoolId: app.globalData.superviseSchoolId
      }),
      dataType: 'json',
      success: res => {
        let accounts = [],
          categoryId = []
        for (let i = 0; i < res.data.length; i++) {
          accounts.push({
            item: res.data[i].category,
            realname: res.data[i].realname,
            checked: false
          })
          categoryId.push(res.data[i].categoryId)
        }
        this.setData({
          accounts: accounts,
          categoryId: categoryId
        })
      },
      fail: res => {
        dd.showToast({
          content: '网络异常！'
        })
      }
    })
  },

  showModal(e) {
    let currentIndex = e.currentTarget.dataset.index
    this.setData({
      currentIndex: currentIndex
    })
    let accounts = this.data.accounts.map((item, index) => {
      return {
        item: item.item,
        checked: index == this.data.superviseContentList[currentIndex].selectedIndex ? true : false,
        realname: item.realname
      }
    })
    let modalComfirmStr = "superviseContentList[" + currentIndex + "].modalComfirm"
    let modalNameStr = "superviseContentList[" + currentIndex + "].modalName"
    this.setData({
      [modalNameStr]: "RadioModal",
      accounts: accounts,
      [modalComfirmStr]: this.data.superviseContentList[currentIndex].selectedIndex != null ? true : false,
      // forwardId: e.currentTarget.dataset.id
    })
  },

  hideModal(e) {
    let modalNameStr = "superviseContentList[" + this.data.currentIndex + "].modalName"
    this.setData({
      [modalNameStr]: null
    })
  },

  radioSelect(e) {
    console.log("e", e)
    let radioIndex = e.currentTarget.dataset.index,
      accounts = this.data.accounts.map((item, index) => {
        return {
          item: item.item,
          checked: index == radioIndex ? true : false,
          realname: item.realname
        }
      }),
      status
    let selectedIndexStr = "superviseContentList[" + this.data.currentIndex + "].selectedIndex"
    let modalComfirmStr = "superviseContentList[" + this.data.currentIndex + "].modalComfirm"
    this.setData({
      accounts: accounts,
      [selectedIndexStr]: radioIndex
    })
    if (this.data.superviseContentList[this.data.currentIndex].selectedIndex != null) status = true
    else status = false
    this.setData({
      [modalComfirmStr]: status
    })
  },

  confirmSelect(e) {
    let modalNameStr = "superviseContentList[" + this.data.currentIndex + "].modalName"
    this.setData({
      // accountIndex: this.data.selectedIndex,
      [modalNameStr]: null
    })
  },

  // 照片
  previewImageDeal: function (e) {
    let itemIndex = parseInt(e.currentTarget.id.split('-')[1])
    let current = e.currentTarget.id.split('-')[2]
    let superviseContent = this.data.superviseContentList[itemIndex]
    dd.previewImage({
      current: current, // 当前显示图片的http链接
      urls: superviseContent.dealFiles // 需要预览的图片http链接列表
    })
  },
  chooseImage: function (e) {
    var that = this;
    dd.chooseImage({
      count: 3,
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: res => {
        dd.showLoading({
          content: "图片上传中"
        })

        let tempImg = res.filePaths
        for (let i = 0; i < tempImg.length; i++) {
          dd.uploadFile({
            url: app.baseUrl + '/DingDingSystem/fileUpload',
            filePath: res.filePaths[i],
            fileName: 'file',
            fileType: 'image',
            header: {
              "Content-Type": "multipart/form-data"
            },
            success: res => {
              if (res.data == "fail") {
                dd.showToast({
                  content: "图片上传失败"
                })
              } else {
                dd.showToast({
                  content: "上传成功"
                })
                // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
                let itemIndex = parseInt(e.currentTarget.id.split('-')[1])
                let superviseContentList = that.data.superviseContentList
                superviseContentList[itemIndex].dealFiles.push(tempImg[i])
                superviseContentList[itemIndex].imageUrl.push(res.data)
                superviseContentList[itemIndex].imageNum++
                that.setData({
                  superviseContentList: superviseContentList
                })
                if (that.data.superviseContentList[itemIndex].dealFiles.length == 3) {
                  superviseContentList[itemIndex].hide = true
                  that.setData({
                    superviseContentList: superviseContentList
                  })
                }
              }
              dd.hideLoading()
            },
            fail: res => {
              dd.hideLoading()
              dd.showToast({
                content: "图片上传失败"
              })
            }
          })
        }

      }
    })
  },

  deleteImage: function (e) {
    let that = this
    let itemIndex = parseInt(e.currentTarget.id.split('-')[1])
    let imgIndex = parseInt(e.currentTarget.id.split('-')[2])
    let superviseContent = this.data.superviseContentList[itemIndex]
    let target = superviseContent.imageUrl[imgIndex]
    let dealFiles = superviseContent.dealFiles[imgIndex]
    let dealFilesStr = "superviseContentList[" + itemIndex + "].dealFiles"
    let imageUrlStr = "superviseContentList[" + itemIndex + "].imageUrl"
    let imageNumStr = "superviseContentList[" + itemIndex + "].imageNum"
    let hideStr = "superviseContentList[" + itemIndex + "].hide"
    let temp = []
    let tempUrl = []
    let dealFilesLength = superviseContent.dealFiles.length
    for (let i = 0; i < dealFilesLength; i++) {
      if (i != imgIndex) {
        temp.push(superviseContent.dealFiles[i])
        tempUrl.push(superviseContent.imageUrl[i])
      }
    }

    dd.showActionSheet({
      items: ['删除这张照片'],
      success: res => {
        if (res.index != -1) {
          that.setData({
            [dealFilesStr]: temp,
            [imageUrlStr]: tempUrl
          })
          dd.httpRequest({
            url: app.baseUrl + '/DingDingSystem/deleteFile',
            method: 'POST',
            headers: {
              "Content-Type": "application/json"
            },
            data: JSON.stringify({
              filename: target.split("image/")[1]
            }),
            dataType: 'text',
            success: res => {
              let imageNum = superviseContent.imageNum - 1
              that.setData({
                [imageNumStr]: imageNum,
              })
              if (dealFilesLength == 3) {
                that.setData({
                  [hideStr]: false
                })
              }
            }
          })
        }
      }
    })
  },

  //视频
  press: function (e) {
    let itemIndex = parseInt(e.currentTarget.id.split('-')[1])
    let superviseContentList = this.data.superviseContentList
    dd.chooseVideo({
      sourceType: ['camera'],
      maxDuration: 10,
      success: res => {
        if (res.size > 2097152) {
          dd.showToast({
            content: '文件大于2M！',
            type: 'fail'
          })
        } else {
          dd.showLoading({
            content: '视频上传中...',
          })
          dd.uploadFile({
            url: app.baseUrl + '/DingDingSystem/fileUpload2',
            filePath: res.filePath,
            fileName: 'file',
            fileType: 'video',
            header: {
              "Content-Type": "multipart/form-data"
            },
            success: res => {
              console.log(res.data)
              superviseContentList[itemIndex].video = res.data
              superviseContentList[itemIndex].videoSrc = app.imageUrl + res.data
              this.setData({
                superviseContentList: superviseContentList
              })
              dd.hideLoading()
            }
          })
        }
      },
      fail(res) {
        console.log("-------调用失败")
      }
    })
  },
  delelteVideo: function (e) {
    let itemIndex = parseInt(e.currentTarget.id.split('-')[1])
    let superviseContentList = this.data.superviseContentList
    let target = superviseContentList[itemIndex].video
    dd.showActionSheet({
      items: ['删除视频'],
      success: res => {
        if (res.index != -1) {
          deleteVideoApi(target.split("video/")[1]).then((res) => {
            if (res.data == "success") {
              superviseContentList[itemIndex].video = ""
              superviseContentList[itemIndex].videoSrc = ""
              this.setData({
                superviseContentList: superviseContentList
              })
            }
          })
        }
      }
    })
  }

})